﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace OPCTreeMonitor.SQLdb.dbConnect
{
    public class SqliteDbHelper
    {
        private static SqlSugarClient _db;
        private static readonly object LockObject = new object();

        public static SqlSugarClient Db
        {
            get
            {
                if (_db == null)
                {
                    lock (LockObject)
                    {
                        if (_db == null)
                        {
                            InitializeDb();
                        }
                    }
                }
                return _db;
            }
        }

        private static void InitializeDb()
        {
            try
            {
                // 读取配置文件
                string configPath = Path.Combine(
                    Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                    "Config",
                    "CommonConfig.json");

                if (!File.Exists(configPath))
                {
                    throw new FileNotFoundException("找不到数据库配置文件", configPath);
                }

                // 解析JSON配置
                dynamic config = Newtonsoft.Json.JsonConvert.DeserializeObject(File.ReadAllText(configPath));
                string connectionString = config.ConnectionStrings.SqliteConnection.ToString();

                // 确保数据库文件路径正确
                string dbPath = connectionString.Split('=')[1].Split(';')[0].Trim();
                if (!Path.IsPathRooted(dbPath))
                {
                    dbPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), dbPath);
                }

                if (!File.Exists(dbPath))
                {
                    throw new FileNotFoundException("找不到SQLite数据库文件", dbPath);
                }

                // 创建SqlSugar连接配置
                _db = new SqlSugarClient(new ConnectionConfig
                {
                    ConnectionString = $"Data Source={dbPath}",
                    DbType = DbType.Sqlite,
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"数据库初始化失败: {ex.Message}");
                throw;
            }
        }
    }
}
